package com.jiangnan.warehouse_management.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiangnan.warehouse_management.dto.request.CreateWarehouse;
import com.jiangnan.warehouse_management.dto.request.WarehouseQueryRequest;
import com.jiangnan.warehouse_management.dto.request.WarehouseRequest;
import com.jiangnan.warehouse_management.dto.response.UserQueryResponse;
import com.jiangnan.warehouse_management.dto.response.WarehouseQueryResponse;
import com.jiangnan.warehouse_management.mapper.WarehouseMapper;
import com.jiangnan.warehouse_management.pojo.Warehouse;
import com.jiangnan.warehouse_management.service.UserService;
import com.jiangnan.warehouse_management.service.WarehouseService;
import lombok.Builder;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;


@Service
@RequiredArgsConstructor
public class WarehouseServiceImpl implements WarehouseService {

    @Autowired
    private final WarehouseMapper  warehouseMapper;
    private final UserService userService;

    @Override
    public WarehouseQueryResponse.Warehouses warehousesById(int id) {
        Warehouse warehouse = new Warehouse();
        warehouse = warehouseMapper.selectById(id);
        WarehouseQueryResponse.Warehouses response = new WarehouseQueryResponse.Warehouses();
        BeanUtils.copyProperties(warehouse, response);
        return response;
    }


    @Override
    public WarehouseQueryResponse getWarehousesInfo(WarehouseQueryRequest request) {
        System.out.println(request.getWarehouseName());
        // 开启分页
        PageHelper.startPage(request.getPage(), request.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<Warehouse> queryWrapper = new LambdaQueryWrapper<>();


        // 添加查询条件
        if (StringUtils.hasText(request.getWarehouseName())) {
            queryWrapper.like(Warehouse::getWarehouseName, request.getWarehouseName());
        }
        if (request.getStatus() != null) {
            queryWrapper.eq(Warehouse::getStatus, request.getStatus());
        }


        // 添加排序
        queryWrapper.orderByDesc(Warehouse::getCreatedAt);

        // 执行查询
        List<Warehouse> warehouses = warehouseMapper.selectList(queryWrapper);

        // 获取分页信息
        PageInfo<Warehouse> pageInfo = new PageInfo<>(warehouses);

        // 构建返回结果
        WarehouseQueryResponse response = new WarehouseQueryResponse();
        response.setTotal(pageInfo.getTotal());
        response.setPage(request.getPage());
        response.setPageSize(request.getPageSize());

        // 转换为 DTO
        List<WarehouseQueryResponse.Warehouses> warehouseDTOs = warehouses.stream()
                .map(warehouse -> {
                    WarehouseQueryResponse.Warehouses dto = new WarehouseQueryResponse.Warehouses();
                    BeanUtils.copyProperties(warehouse, dto);

                    // 设置manager信息（需要根据managerId查询用户表）
                    UserQueryResponse.QueryUserDTO manager = userService.findById(warehouse.getManagerId());
                    if (manager != null) {
                        WarehouseQueryResponse.Warehouses.ManagerDTO managerDTO =
                                new WarehouseQueryResponse.Warehouses.ManagerDTO();
                        managerDTO.setUserId(manager.getUserId());
                        managerDTO.setUsername(manager.getUsername());
                        managerDTO.setRealName(manager.getRealName());
                        dto.setManager(managerDTO);
                    }

                    return dto;
                })
                .collect(Collectors.toList());

        response.setList(warehouseDTOs);

        return response;
    }


    @Override
    public Warehouse createWarehouse(CreateWarehouse request) {
        // 检查是否存在对应的userId
        UserQueryResponse.QueryUserDTO user = userService.findById(request.getManagerId());
        if (user == null) {
            throw new IllegalArgumentException("无效的管理员ID: " + request.getManagerId());
        }

        // 创建并插入仓库
        Warehouse warehouse = new Warehouse();
        BeanUtils.copyProperties(request, warehouse);
        warehouseMapper.insert(warehouse);

        return warehouse;
    }

    @Override
    public Warehouse updateWarehouse(int id, WarehouseRequest request) {
        Warehouse warehouse = new Warehouse();
        BeanUtils.copyProperties(request, warehouse);
        warehouse.setWarehouseId(id);
        warehouseMapper.updateById(warehouse);
        return warehouseMapper.selectById(id);
    }

    @Override
    public void deleteWarehouse(int id) {
        warehouseMapper.deleteById(id);
    }
}
